from django.contrib.auth.models import AnonymousUser
from .models import SysUser


def jwt_get_username_from_payload_handler(payload):
    """
    从JWT payload中获取用户名
    自定义JWT payload处理器，用于从payload中提取用户名
    """
    username = payload.get('username')
    return username


def jwt_payload_handler(user):
    """
    自定义JWT payload处理器
    为SysUser模型创建JWT payload
    """
    payload = {
        'user_id': user.id,
        'username': user.username,
        'email': user.email,
    }
    return payload


class JWTAuthentication:
    """
    自定义JWT认证类
    用于处理基于JWT的用户认证
    """

    @staticmethod
    def authenticate_credentials(token):
        """
        验证JWT令牌并返回用户
        """
        try:
            # 使用 simplejwt 替代方案
            from rest_framework_simplejwt.tokens import AccessToken
            access_token = AccessToken(token)
            user_id = access_token['user_id']
            if user_id:
                user = SysUser.objects.get(id=user_id)
                return user
        except (SysUser.DoesNotExist, Exception):
            pass
        return AnonymousUser()
